class ArkTransformer {
  name = "ark";

  constructor(options) {
    this.max_tokens = options.max_tokens || 32768;
    this.max_input_tokens = options.max_input_tokens || 31000; // Input token limit
    this.enable_thinking = options.enable_thinking || false;
    this.stream = options.stream || true;
    this.temperature = options.temperature || 0.6;
    this.top_p = options.top_p || 0.9;
  }

  // Simple token estimation function (approximation)
  estimateTokenCount(text) {
    if (!text || typeof text !== 'string') return 0;
    // Rough estimation: 1 token ≈ 4 characters for English, 1-2 characters for Chinese
    // This is a conservative estimate
    const englishChars = text.match(/[a-zA-Z0-9\s\.,!?;:\-'"()[\]{}]/g)?.length || 0;
    const otherChars = text.length - englishChars;
    return Math.ceil(englishChars / 4 + otherChars / 1.5);
  }

  // Calculate total input tokens from messages
  calculateInputTokens(messages) {
    if (!Array.isArray(messages)) return 0;
    
    let totalTokens = 0;
    for (const message of messages) {
      if (message.content) {
        if (typeof message.content === 'string') {
          totalTokens += this.estimateTokenCount(message.content);
        } else if (Array.isArray(message.content)) {
          // Handle multimodal content
          for (const content of message.content) {
            if (content.type === 'text' && content.text) {
              totalTokens += this.estimateTokenCount(content.text);
            }
            // Note: Image tokens are much more complex to estimate, 
            // so we add a conservative estimate
            else if (content.type === 'image') {
              totalTokens += 1000; // Conservative estimate for image
            }
          }
        }
      }
      
      // Add tokens for role and other metadata (small overhead)
      if (message.role) {
        totalTokens += 5;
      }
    }
    
    return totalTokens;
  }

  async transformRequestIn(request, provider) {
    // Check input token limit before processing
    if (request.messages) {
      const inputTokens = this.calculateInputTokens(request.messages);
      
      if (inputTokens > this.max_input_tokens) {
        // Create an error response without calling the API
        const error = new Error(`Input token count (${inputTokens}) exceeds maximum limit (${this.max_input_tokens}). Please reduce the input length and try again.`);
        error.code = 'INPUT_TOKEN_LIMIT_EXCEEDED';
        error.inputTokens = inputTokens;
        error.maxInputTokens = this.max_input_tokens;
        throw error;
      }
      
      // Log token usage for monitoring
      if (process.env.LOG === 'true' || process.env.LOG === true) {
        console.log(`[ArkTransformer] Input tokens: ${inputTokens}/${this.max_input_tokens}`);
      }
    }
    
    // Set the standard OpenAI-compatible parameters
    request.max_tokens = this.max_tokens;
    request.stream = this.stream;
    request.temperature = this.temperature;
    request.top_p = this.top_p;
    
    // Handle Ark-specific parameters if needed
    if (this.enable_thinking) {
      request.enable_thinking = this.enable_thinking;
    }
    
    // Ensure the request follows OpenAI format for compatibility
    if (!request.messages) {
      request.messages = [];
    }
    
    return request;
  }

  async transformResponseOut(response, provider) {
    // Handle response transformation if needed
    // Ark API should be OpenAI-compatible, so minimal transformation required
    return response;
  }
}

module.exports = ArkTransformer;
